<template>
	<uni-datetime-picker
		:type="type"
		v-model="innerValue"
		ref="control"
	>
		<view class="ui-datetime-select__handle">
			<view class="ui-datetime-select__icon">
				<ui-icon name="calendar-2-line"></ui-icon>
			</view>
			<view
				class="ui-datetime-select__placeholder"
				v-if="!hasValue"
			>{{ placeholder }}</view>
			<view v-else class="ui-datetime-select__value">
				{{ showValue }}
			</view>
		</view>
	</uni-datetime-picker>
</template>

<script>
	import { mapActions } from 'vuex'
	import { formatDate } from '@/utils/date.js'
	import { unique } from '@/utils/string.js'

	export default {
		name:"BiDatetimeSelect",
		props: {
			type: {
				type: String,
				default: 'date'
			},
			value: {
				type: [String, Array, Date]
			},
			placeholder: {
				type: String
			}
		},
		data() {
			return {
			}
		},
		computed: {
			innerValue: {
				get () {
					return this.value
				},
				set (val) {
					this.$emit('input', val)
				}
			},
			hasValue () {
				if (Array.isArray(this.value)) {
					return !!this.value.length
				} else {
					return !!this.value
				}
			},
			showValue () {
				if (!this.hasValue) {
					return
				}
				if (Array.isArray(this.value)) {
					return this.value.map(v => formatDate(v, 'YYYY-mm-dd')).join(' ~ ')
				} else {
					return formatDate(this.value, 'YYYY-mm-dd')
				}
			},
			innerValue: {
				get () {
					return this.value
				},
				set (val) {
					this.$emit('input', val)
				}
			}
		},
		mounted () {
			this.$nextTick(() => {
				if (this.$refs.control && this.$refs.control.$refs.mobile) {
					this.$refs.control.$refs.mobile.$watch('show', (visible) => {
						this.handlePopupVisibleChange(visible)
					})
				}
			})
		},
		created () {
			this.id = unique()
		},
		methods: {
			...mapActions([
				'AddPagePopupActiveNum',
				'DelPagePopupActiveNum'
			]),
			handlePopupVisibleChange (show) {
				if (show) {
					this.AddPagePopupActiveNum(this.id)
				} else {
					this.DelPagePopupActiveNum(this.id)
				}
			}
		},
		beforeDestroy () {
			this.DelPagePopupActiveNum(this.id)
		}
	}
</script>

<style lang="less">
.ui-datetime-select__handle{
	height: 32px;
	line-height: 32px;
	display: flex;
	flex-direction: row;
	align-items: center;
	position: relative;
	&:after {
		content: '';
		position: absolute;
		right: 6px;
		top: 50%;
		transform: translateY(-50%) rotate(45deg);
		margin-top: -3px;
		width: 6px;
		height: 6px;
		border: 1px solid #ccc;
		border-left-color: transparent;
		border-top-color: transparent;
	}
}
.ui-datetime-select__icon{
	margin-right: 9px;
	opacity: .4;
}
.ui-datetime-select__placeholder,
.ui-datetime-select__value{
	color: #999;
}
</style>
